package org.soria.getinfo.utils;

import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;

public class FontUtil {
    private static final Font GLOBAL;
    public static final Font DEFAULT;
    public static final Font TITLE;
    static {
        GLOBAL = getCustomFont(ResUtil.getString("font.global.path"), Font.PLAIN, 17);
        DEFAULT = getCustomFont(ResUtil.getString("font.default.path"), Font.BOLD, 17);
        TITLE = getCustomFont(ResUtil.getString("font.title.path"), Font.PLAIN, 20);
    }
    // 自定义字体
    private static Font getCustomFont(String fontPath, int style, int size) {
        try {
            URL url = FontUtil.class.getResource(fontPath);
            File fontFile = new File(url.getFile());
            Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
            return font.deriveFont(style, size);
        } catch (IOException e) {
            System.out.println(e.getMessage() + ": 无法读取文件" + fontPath);
        } catch (FontFormatException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    // 设置全局字体
    public static void initGlobalFont() {
        FontUIResource fontRes = new FontUIResource(GLOBAL);
        for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof FontUIResource) {
                UIManager.put(key, fontRes);
            }
        }
    }
}
